#include "MTableWidget.h"
#include  <QApplication>

MTableWidget::MTableWidget(QWidget * parent )  :
    QTableWidget(parent)
{

    this->setDragEnabled(true);
    this->setAcceptDrops(true);//设置QListWidget的Item项可以被拖拽
	setDragDropMode(QAbstractItemView::DragDrop);
	setDropIndicatorShown(true);//显示下拉

    //设置单击选择一行
    this->setSelectionBehavior(QAbstractItemView::SelectRows);//整行选中的方式
    //设置每行内容不可编辑
    this->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //设置只能选择一行，不能选择多行
    this->setSelectionMode(QAbstractItemView::SingleSelection);
    this->setTextElideMode(Qt::ElideMiddle);
}

void MTableWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
        startPos = event->pos();
    QTableWidget::mousePressEvent(event);
}

void MTableWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        int distance = (event->pos() - startPos).manhattanLength();
        if (distance >= QApplication::startDragDistance())
            performDrag();

    }

    QTableWidget::mouseMoveEvent(event);
}

void MTableWidget::dragEnterEvent(QDragEnterEvent *event)
{
    MTableWidget *source =
            qobject_cast<MTableWidget *>(event->source());
    if (source && source != this) {
        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}

void MTableWidget::dragMoveEvent(QDragMoveEvent *event)
{
	
    MTableWidget *source =
            qobject_cast<MTableWidget *>(event->source()); //判断是不是自己
    if (source && source != this) {
        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}

void MTableWidget::dropEvent(QDropEvent *event)
{
    MTableWidget *source =
            qobject_cast<MTableWidget *>(event->source());
    if (source && source != this) {

        QList<QUrl> urlList = event->mimeData()->urls();
        int row = this->rowCount();
        this->setRowCount(row+1);
       for(int i =0;i<urlList.count();i++)
       {
          QUrl qUrl = urlList[i];
          QTableWidgetItem *item = new QTableWidgetItem(qUrl.toString());

          this->setItem(row,i,item);
       }
        event->setDropAction(Qt::MoveAction);
        event->accept();
    }
}

void MTableWidget::performDrag()
{
    QTableWidgetItem  *item1;
    int row = this->currentRow();
    if (row>=0) {
        QList<QUrl> urlList;
        urlList.clear();

        for(int i =0;i<this->columnCount();i++)
        {
           item1 = this->item(row,i);
           if(item1){
           QUrl qUrl(item1->text());
           urlList.append(qUrl);
           }
        }
        QMimeData *mimeData = new QMimeData;
        mimeData->setUrls(urlList);

        QDrag *drag = new QDrag(this);
        drag->setMimeData(mimeData);
        drag->setPixmap(QPixmap(":/images/person.png"));
        if (drag->exec(Qt::MoveAction) == Qt::MoveAction)
            this->removeRow(row);//删除行
    }
}
